package org.example.diary.entity.dto;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.example.diary.entity.dao.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private SysUser sysUser;

    //存储权限信息
    private List<String> permissions;

    public LoginUser(SysUser sysUser, List<String> permissions) {
        this.sysUser = sysUser;
        this.permissions = permissions;
    }

    //存储SpringSecurity所需要的权限信息的集合
    @JSONField(serialize = false) // 不进行序列化
    private List<GrantedAuthority> authorities;


    // 获取权限
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (!ObjectUtil.isNull(authorities)) {
            return authorities;
        }
        authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    // 获取密码
    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    // 获取用户名
    @Override
    public String getUsername() {
        return sysUser.getUsername();
    }

    // 判断是否过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 判断是否锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 判断证书是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
